<?php
/**
 * 文字广播
 * User: ws
 * Date: 2018/8/31
 * Time: 17:14
 */

namespace app\admin\controller;
use think\Db;
use app\admin\model\Broadcast as bModel;
class Broadcast extends Init
{
    function index(){
        if ($this->request->isAjax()) {
            $key = input('key')?input('key'):'';
            $where['content'] = array('like','%'.trim($key).'%');
            $list = bModel::where($where)->order('broadcast_id desc')->paginate(input('limit'))->toArray();
            foreach ($list['data'] as $key=>$item){
                $user = Db::name('user')->where("user_id={$item['user_id']}")->field('name')->find();
                $list['data'][$key]['user_id'] = $user['name'];
            }
            return json($result = ['code'=>0,'msg'=>'获取成功','data'=>$list['data'],'count'=>$list['total']]);
        }
        return view('list');
    }


    function add(){
        if(request()->isPost()){
            $data = $this->request->post();
            if (!bModel::create($data)) {
                return json(array('code'=>0,'msg'=>'添加失败'));
            }
            return json(array('code'=>200,'msg'=>'添加成功'));
        }
        $user = Db::name('user')->field('user_id,name')->select();
        return view('add',['user'=>$user]);
    }




    function edit(){
        if(request()->isPost()){
            $data = $this->request->post();
            if (!bModel::update($data)) {
                return json(array('code'=>0,'msg'=>'修改失败'));
            }
            return json(array('code'=>200,'msg'=>'修改成功'));
        }

        $list = bModel::where('broadcast_id', input('id'))->find()->toArray();
        $user = Db::name('user')->field('user_id,name')->select();
        return view('edit',['list'=>$list,'user'=>$user]);
    }



    function del(){
        $id = input('id');
        if (!bModel::destroy(['broadcast_id' => $id])) {
            return json(array('code'=>0,'msg'=>'删除失败'));
        }
        return json(array('code'=>200,'msg'=>'删除成功'));
    }
}